<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	/* 首页 */
	public function index()
	{
		//$this->load->view('welcome_message');
		//var_dump($this->session->userdata('isLogin'));
		$action = $this->input->get('action');
		if (empty($action)) $action = 'user';
		$data = array();
		$data = $this->_initViewData();
		$data['action'] = $action;
		$this->load->view('welcome/welcome_index', $data);
	}
	
	/* 后台管理 */
	public function manage()
	{
		$data = array();
		$data = $this->_initViewData();
		$this->load->view('welcome/manage_index', $data);
	}
	
	/* 初始化视图数据 */
	private function _initViewData() {
		$data = array();
		$data['adminMenu'] = $this->_loadMenu();
		$data['menu'] = $this->_fixMenuResult(0, $data['adminMenu']);
		$data['bottomMenu'] = array();
		for ($i = 0; $i < 3; $i++) {
			$data['bottomMenu'][] = $data['menu'][$i];
		}
		//var_dump($data['bottom_menu']);
		$data['wallpapers'] = $this->_loadWallpapers();
		$data['isLogin'] = $this->session->userdata('isLogin');
		$data['userLogin'] = $this->session->userdata('userLogin');
		return $data;
	}
	
	/* 读取菜单数据 */
	private function _loadMenu() {
		$output= array();
		$query = $this->db->get('menu');
		foreach ($query->result_array() as $row)
		{
    		$output[] =  $row;
		}
		
		return $output;
	}
	
	/* 树状结构 */
	function _fixMenuResult($parentId, $source) 
	{
		$result = array();
    	foreach ($source as $item)
    	{
    		if ($item['is_show'] == '0') continue;
        	if ($item['parent_id'] == $parentId)
        	{
            	$item['children'] = $this->_fixMenuResult($item['id'], $source);
            	$result[] = $item;
        	}
    	}
    	
    	return $result;
	}
	
	/* 读取壁纸 */
	private function _loadWallpapers()
	{
		$output = array();
		$wallpapersPath = APPPATH . '../' . 'wallpapers';
		$handler = opendir($wallpapersPath);
		
		while (($fileName = readdir($handler)) !== false) {
			//
			if ($fileName === '.' || $fileName === '..') {
				continue;
			}
			if (!mb_check_encoding($fileName, 'utf-8')) {
				$fileName = mb_convert_encoding($fileName, 'utf-8', 'gb2312');
			}
			$output[] = array('url' => 'wallpapers/' . $fileName, 'name' => $fileName);
		}
		return $output;
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */